package br.edu.ufcg.dsc.actions.user;

import org.apache.struts2.config.ParentPackage;
import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.apache.struts2.dispatcher.ServletDispatcherResult;
import org.apache.struts2.dispatcher.ServletRedirectResult;

import br.edu.ufcg.dsc.domain.User;
import br.edu.ufcg.dsc.services.UserService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

@Results(value = {
		@Result(name = "success", type = ServletRedirectResult.class, value = "/index.action?message=You logged in."),
		@Result(name = "input", type = ServletDispatcherResult.class, value = "/jsp/user/login.jsp") 
		}
)
@ParentPackage(value = "myPackage")
@Validations(requiredStrings = {
		@RequiredStringValidator(fieldName = "login", key = "user.login.mandatory", message = "Default Message"),
		@RequiredStringValidator(fieldName = "password", key = "user.password.mandatory", message = "Default Message")
		}
)
public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 8723969851239730089L;

	private String login, password;

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	private User user;

	@Override
	public void validate() {
		if (login == null) {
			addFieldError("login", getText("user.login.failed"));
			return;
		}

		user = UserService.find(login);

		if (user == null || !password.equals(user.getPassword()))
			addFieldError("login", getText("user.login.failed"));
	}

	@SuppressWarnings("unchecked")
	@Override
	public String execute() throws Exception {
		ActionContext.getContext().getSession().put("user", user);
		return super.execute();
	}
}
